package com.hzdl.hotel.controller;

import com.github.pagehelper.PageInfo;
import com.hzdl.hotel.bean.Administer;
import com.hzdl.hotel.bean.Check;
import com.hzdl.hotel.bean.Menu;
import com.hzdl.hotel.mapper.AdministerMapper;
import com.hzdl.hotel.service.AdministerService;
import com.hzdl.hotel.service.LogService;
import com.hzdl.hotel.service.MenuService;
import com.hzdl.hotel.util.AJAXResult;
import com.hzdl.hotel.util.ConnUtil1;
import com.hzdl.hotel.util.TreeNode;
import com.hzdl.hotel.vo.AdministerVo;
import com.hzdl.hotel.vo.LogVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.xml.AbstractJaxb2HttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdministerController {

    @Autowired
    private AdministerService as;
    @Autowired
    private MenuService ms;
    @Autowired
    private LogService ls;



    @RequestMapping("/loginInit")
    public String loginInit(){
        return "administer/login";
    }

    @RequestMapping("/login")
    public String login(Model model, AdministerVo adminVo, HttpSession session, HttpServletRequest request){
        Administer admin = as.findAdministerByWhere(adminVo);
        Object obj =session.getAttribute("AUTOYZM");
        if(obj!=null){
            String yzm = (String)obj;
        }
        if(admin==null){
            model.addAttribute("msg","账号与密码不匹配");
            return "redirect:/admin/loginInit";
        }else{
            LogVo logVo = new LogVo();
            logVo.setLoginName(admin.getLoginName()+"-"+admin.getRealName());
            //获取ip地址
            String ip=request.getRemoteAddr();
            logVo.setLoginIP(ip);
            ls.insertLog(logVo);
            session.setAttribute("admin",admin);
            return "administer/index";
        }

    }

    @RequestMapping("/generateYzm")
    public void generateYzm(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String autoYzm = ConnUtil1.generateVerifyCode(4);
        req.getSession().setAttribute("AUTOYZM",autoYzm);
        //输出指定验证码图片流
        ConnUtil1.outputImage(100,30,resp.getOutputStream(),autoYzm);
    }
    @RequestMapping("/chkYzm")
    public void chkYzm(HttpServletRequest req,HttpServletResponse resp,String code1) throws IOException {
        String yzm=(String)req.getSession().getAttribute("AUTOYZM");
        int  i =0;
        if(!code1.equalsIgnoreCase(yzm)){
            i=1;
        }
        PrintWriter out = resp.getWriter();
        out.print(i);
        out.close();
    }
    @RequestMapping("/deskManagerInit")
    public String deskManagerInit(){
        return "administer/deskManager";
    }

    @RequestMapping("/findCheck")
    @ResponseBody
    public AJAXResult findCheck(){
        List<Check> cList=as.findCheck();
        return new AJAXResult(0,"",cList,new Long(5));
    }

    @RequestMapping("/leftMenu")
    @ResponseBody
    public Map<String,Object> leftMenu(HttpSession session){
       Map<String,Object> map = new HashMap<>();
       Object object = session.getAttribute("admin");
       if(object!=null){
           Administer admin = (Administer)object;
           List<Menu> all = null;
           if(admin.getId()!=null&&admin.getId()==1){
               all=ms.findAllMenu();
           }else{
           all=ms.findByUserId(admin.getId());
           }
           List<TreeNode> treeNodes = new ArrayList<>();
           // 查询出来的菜单集合 转换为 需要的类型TreeNode（页面需要的类型）
           for(Menu menu:all){
               TreeNode treeNode = new TreeNode(menu.getId(),menu.getPId(),
                       menu.getName(),menu.getIcon(),
                       menu.getHref(),menu.getOpen()==1?true:false);
               treeNodes.add(treeNode);
           }
           List<TreeNode> treeNodeList = new ArrayList<>();
           // 区分一级菜单还是二级菜单
           for(TreeNode treeNode:treeNodes){
               if(treeNode.getPid()!=null&&treeNode.getPid()==1){
                   treeNodeList.add(treeNode);
                   continue;
               }
               for(TreeNode treeNode1:treeNodeList){
                   if(treeNode.getPid() != null && treeNode.getPid() == treeNode1.getId()){
                       treeNode1.getChildren().add(treeNode);
                   }
               }
           }
           map.put("contentManagement",treeNodeList);
       }
           return map;
    }
    @RequestMapping("/adminManageInit")
    public String adminManageInit(){
        return "administer/administerManage";
    }

    @RequestMapping("/administerShow")
    @ResponseBody
    public AJAXResult administerShow(AdministerVo administerVo){
        if (administerVo.getPage() == null) {
            administerVo.setPage(1);
        }
        if (administerVo.getLimit() == null) {
            administerVo.setLimit(5);
        }
        PageInfo pageInfo = as.findAdministerByWhere1(administerVo);
        return new AJAXResult(0, "", pageInfo.getList(), pageInfo.getTotal());

    }
    @RequestMapping("/addAdminister")
    @ResponseBody
    public AJAXResult addAdminister(AdministerVo administerVo){
        int row=as.addAdminister(administerVo);
        if(row!=0){
            return AJAXResult.ADD_SUCCESS;
        }else{
            return AJAXResult.ADD_ERROR;
        }
    }

    @RequestMapping("/updateAdmin")
    @ResponseBody
    public AJAXResult updateAdmin(AdministerVo administerVo){
        int row=as.updateAdminister(administerVo);
        if(row!=0){
            return AJAXResult.UPDATE_SUCCESS;
        }else{
            return AJAXResult.UPDATE_ERROR;
        }
    }

    @RequestMapping("/adminDelete")
    @ResponseBody
    public AJAXResult adminDelete(Integer aId){
        int row=as.deleteRoleByAId(aId);
        row+=as.deleteAdminister(aId);
        if(row!=0){
           return new AJAXResult(1,"您已解雇该员工");
       }else{
           return AJAXResult.DELETE_ERROR;
       }
    }

    @RequestMapping("/deleteAllAdmin")
    @ResponseBody
    public AJAXResult deleteAllAdmin(String ids){
        String[] id= ids.split(",");
        int row=0;
        for(int i=0;i<id.length;i++){
            row+=as.deleteRoleByAId(Integer.valueOf(id[i]));
           row+=as.deleteAdminister(Integer.valueOf(id[i]));
           }
        if(row!=0){
            return new AJAXResult(1,"您已解雇您所勾选的员工");
        }else{
            return AJAXResult.DELETE_ERROR;
        }
    }

     @RequestMapping("/findRoleByAdmin")
    @ResponseBody
    public AJAXResult findRoleByAdmin(Integer id){
        return new AJAXResult(0,"",as.findRole(id));
     }

    @RequestMapping("/saveRoleAdmin")
    @ResponseBody
    public AJAXResult saveRoleAdmin(AdministerVo administerVo){

        int row = as.updateRoleAdmin(administerVo);
        if(row == 0){
            return AJAXResult.DISPATCH_ERROR;
        }

        return AJAXResult.DISPATCH_SUCCESS;
    }






}
